package restful;

import static restful.Matchers.*;

import java.util.*;

public class RestfulProtocolMatcher {

	public static final RestfulProtocolMatcher matcher(RestfulProtocol protocol) {
		return new RestfulProtocolMatcher().using(protocol);
	}

	private Set<String> matchers = new TreeSet<String>(new PatternComparator());

	private Map<String, RestfulMethod> methods = new LinkedHashMap<String, RestfulMethod>();

	public RestfulProtocolMatcher() {}

	public boolean matches(String uri) {
		for (String matcher : matchers)
			if (uri.matches(matcher)) return true;

		return false;
	}

	public RestfulMethod method(String uri) {
		for (String matcher : matchers) {
			if (uri.matches(matcher)) return methods.get(matcher).apply(uri);
		}
		return null;
	}

	public String signatureOf(String uri) {
		return Signatures.topicSignatureOf(method(uri));
	}

	@Override
	public String toString() {
		return matchers.toString();
	}

	public RestfulProtocolMatcher using(RestfulProtocol protocol) {
		index(protocol.getMethods());
		return this;
	}

	protected void index(List<RestfulMethod> inputMethods) {
		for (RestfulMethod method : inputMethods) {
			for (String methodMatcher : matchersOf(method)) {
				matchers.add(methodMatcher);
				methods.put(methodMatcher, method);
			}
		}
	}

	public static Comparator<String> patternComparator() {
		return new PatternComparator();
	}
}
